import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Bully } from 'app/shared/service';
import { MESSAGE_CHANNEL } from 'app/app.constants';

@Injectable()
export class MapMessageService {
    protected broadcast$: BehaviorSubject<Bully>;
    constructor() {
        if (!this.broadcast$) {
            this.broadcast$ = new BehaviorSubject<Bully>(null);
        }
    }

    public sendMessage(item: Bully) {
        this.broadcast$.next(item);
    }

    public getMessage() {
        return this.broadcast$.asObservable();
    }

    // 注册语言通讯频道,并接受消息
    public registerLanguageChannel(channel: MESSAGE_CHANNEL) {
        const Broadcast = new BroadcastChannel(channel);
        /* Broadcast.onmessage = (_e: any) => {
            if (!_e) { return; }
            this.sendMessage(_e['data']);
		}; */
        Broadcast.addEventListener('message', (res: any) => {
            if (!res) {
                return;
            }
            this.sendMessage(res['data']);
        });
    }
}
